package gl.training.basics;

class AnagramsDemo {
	public static void main(String[] args) {
		//----------------------- inputing -------------------------------
		System.out.println("***** Anagram *****");		
		String str1 = requestString("Input 1st phrase: ");
		String str2 = requestString("Input 2nd phrase: ");
		//----------------------- calculating ----------------------------
		String seq1 = getSequence(str1);
		String seq2 = getSequence(str2);
		if(seq1.equals(seq2)) {
			System.out.println("Answer: Anagrams");
		} else {
			System.out.println("Answer: Not anagrams");
		}
		//System.out.println("'"+seq1+"'");
		//System.out.println("'"+seq2+"'");					
		
	}

	private static String getSequence(String str) {
		str = str.toLowerCase();
		int len = str.length(),
			n = 0; // len without whitespaces
		char[] C = new char[len];
		for(int i=0; i<len; i++)
			if((str.charAt(i) != ' ')
			&&(str.charAt(i) != '\t')) {
				C[n] = str.charAt(i);
				n++;
			}
		// "Bubble" forever		
		boolean changed;		
		do{
			changed = false;
			for(int i=1; i<n; i++) {
				int a = C[i-1], b = C[i];
				 if(a > b) {
					char t = C[i-1];
					C[i-1] = C[i];
					C[i] = t;
					changed = true;
				}		
			}
		}while(changed);
		return new String(C, 0, n);
	}
	
	private static String requestString(String msg) {		
		System.out.print(msg);
		String str = "";
		try {
			byte[] buf = new byte[256];
			int q = System.in.read(buf, 0, 255);
			str = new String(buf, 0, q-2);
		} catch(java.io.IOException e) {
			System.out.println("An error has occurs.");
		}		
		return str;
	}
}